import { deleteArticleApi, getOneselfArticleList } from '@/services/articles/index';
import useRequest from '@ahooksjs/use-request';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Select, Space, Switch, Tag } from 'antd';
import type { SortOrder } from 'antd/lib/table/interface';
import React, { useRef } from 'react';

const articleIsOverheadChnage = (val: boolean) => {
  console.log(val);
};

const queryData = async (
  params: COMMON.TableParams = { current: 1, pageSize: 20 },
  sort?: Record<string, SortOrder>,
) => {
  const { data: { records = [], total } = {} } = await getOneselfArticleList({
    ...params,
    sort: sort?.articleLookCount,
  });
  return {
    data: records,
    success: true,
    total,
  };
};

const Index: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const { run: deleteArticleRun } = useRequest(deleteArticleApi, {
    manual: true,
    onSuccess(data) {
      const { code, message: errorMessage } = data;
      if (code === 200) {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(errorMessage);
      }
    },
  });
  const tableAlertOptionRender = ({
    selectedRows,
    onCleanSelected,
  }: COMMON.TableAlert<ARTICLEAPI.ARTICLE>) => {
    const articleIds = selectedRows.map((item) => item.articleId);
    return (
      <Space size={24}>
        <span>
          <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
            取消已选择
          </a>
          <a
            style={{ marginInlineStart: 8, color: 'red' }}
            onClick={() => deleteArticleRun({ articleIds })}
          >
            删除已选择
          </a>
        </span>
      </Space>
    );
  };
  const columns: ProColumns<ARTICLEAPI.ARTICLE>[] = [
    {
      title: '标题',
      dataIndex: 'articleTitle',
      fixed: 'left',
      ellipsis: true,
    },
    {
      title: '标签',
      dataIndex: 'articleLabelList',
      renderText: (v) => {
        let renders = null;
        console.log(v);
        if (v) {
          renders = v.map((item: ARTICLEAPI.ArticleLabe) => {
            return (
              <Tag key={item.articleLabelId} color="blue">
                {item.articleLabelName}
              </Tag>
            );
          });
        }
        return <div>{renders}</div>;
      },
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Select
            // 自定义配置
            placeholder="请选择标签"
            options={[
              {
                value: 'java',
                label: 'java',
              },
              {
                value: 'css',
                label: 'css',
              },
            ]}
          />
        );
      },
    },
    {
      title: '置顶',
      dataIndex: 'articleIsOverhead',
      render: (val) => {
        return (
          <Switch defaultChecked={val as unknown as boolean} onChange={articleIsOverheadChnage} />
        );
      },
      renderFormItem: () => {
        return (
          <Select
            // 自定义配置
            options={[
              {
                value: 1,
                label: '是',
              },
              {
                value: 0,
                label: '否',
              },
            ]}
          />
        );
      },
    },
    {
      title: '浏览量',
      dataIndex: 'articleLookCount',
      search: false,
      sorter: true,
    },
    {
      title: '发表时间',
      dataIndex: 'articleCreationTime',
      valueType: 'dateTime',
      sorter: true,
      search: false,
    },
    {
      title: '最后修改时间',
      dataIndex: 'articleAmendTime',
      valueType: 'dateTime',
      sorter: true,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (t, record) => [
        <a
          key="editable"
          onClick={() => {
            window.open(`/admin/articlemanage/articles/edit/${record.articleId}`);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title="确定删除吗,删除后暂不能恢复哦!!!"
          okText="确定"
          cancelText="取消"
          onConfirm={() => deleteArticleRun({ articleIds: [record.articleId] })}
        >
          <a key="delete" style={{ color: 'red' }}>
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<ARTICLEAPI.ARTICLE>
        columns={columns}
        request={queryData}
        actionRef={actionRef}
        rowSelection={{}}
        tableAlertOptionRender={tableAlertOptionRender}
        rowKey="articleId"
        pagination={{
          showQuickJumper: true,
        }}
        dateFormatter="string"
        headerTitle="文章列表"
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              window.open('/admin/articlemanage/articles/add');
            }}
          >
            新增文章
          </Button>,
        ]}
      />
    </PageContainer>
  );
};

export default Index;
